#include "ThreatMap.h"



ThreatMap::ThreatMap()
{
	rows = BWAPI::Broodwar->mapHeight();
	cols = BWAPI::Broodwar->mapWidth();
	dpsMap = new int[rows*cols];
	memset(dpsMap, 0, rows*cols*sizeof(dpsMap[0]));
}

ThreatMap::~ThreatMap()
{
	if(dpsMap) {
		delete[] dpsMap;
		dpsMap = 0;
	}
}

void ThreatMap::Refresh()
{
	memset(dpsMap, 0, rows*cols*sizeof(dpsMap[0]));
	std::set<BWAPI::Player*>::iterator playersBegin = BWAPI::Broodwar->enemies().begin();
	std::set<BWAPI::Player*>::iterator playersEnd = BWAPI::Broodwar->enemies().end();
	while(playersBegin != playersEnd)
	{
		BWAPI::Player* player = *playersBegin;
		std::set<BWAPI::Unit*>::const_iterator enemyUnitsBegin = player->getUnits().begin();
		std::set<BWAPI::Unit*>::const_iterator enemyUnitsEnd = player->getUnits().end();
		while(enemyUnitsBegin != enemyUnitsEnd)
		{
			const BWAPI::Unit* enemyUnit = *enemyUnitsBegin;
			BWAPI::WeaponType weapon = enemyUnit->getType().groundWeapon();
			int rangePixels = weapon.maxRange();
			int rangeTiles = rangePixels/32;
			if(rangeTiles<=0)
				rangeTiles = 1;
			AddInfluence(enemyUnit->getTilePosition(), weapon.damageAmount()*24/(1+weapon.damageCooldown()), rangeTiles);
			enemyUnitsBegin++;
		}
		playersBegin++;
	}
}

void ThreatMap::AddInfluence(BWAPI::TilePosition tile, int amount, int range)
{
	if(amount < 1)
		amount = 1;
	for(int r=tile.y()-range;r<=tile.y()+range;r++) {
		for(int c=tile.x();c<=tile.x()+range;c++) {
			if(c>=0 && c<cols && r>=0 && r<rows) {
				int diffX = c-tile.x();
				int diffY = r-tile.y();
				if(diffX*diffX + diffY*diffY <= range*range) {
					dpsMap[r*cols+c] += amount;
				}
			}
		}
	}
}

void ThreatMap::DebugDraw()
{
	BWAPI::TilePosition topLeftCameraPos(BWAPI::Broodwar->getScreenPosition());
	
	const int MaxRows = 1200/32;
	const int MaxCols = 1920/32;
	for(int r=topLeftCameraPos.y();r<topLeftCameraPos.y()+MaxRows;r++) {
		for(int c=topLeftCameraPos.x();c<topLeftCameraPos.x()+MaxCols;c++) {
			BWAPI::Broodwar->drawTextMap(c*32+8, r*32+8, "%d", dpsMap[r*cols+c]);
		}
	}
}
